from django.contrib.auth.backends import ModelBackend
from django.contrib.auth import get_user_model

User = get_user_model()


class MultipleLoginBackend(ModelBackend):
    """
    自定义认证后端，支持用户名、邮箱、手机号多种方式登录
    继承ModelBackend保留所有默认功能（权限检查、状态检查等）
    """

    def authenticate(self, request, username=None, password=None, **kwargs):
        """
        认证用户
        :param request: 请求对象
        :param username: 用户输入的登录名（可能是用户名、邮箱或手机号）
        :param password: 密码
        :return: 用户对象或None
        """
        if username is None or password is None:
            return None

        user = None

        # 1. 首先尝试用用户名登录
        try:
            user = User.objects.get(username=username)
        except User.DoesNotExist:
            pass

        # 2. 如果用户名找不到，尝试用邮箱登录
        if user is None:
            try:
                user = User.objects.get(email=username)
            except User.DoesNotExist:
                pass

        # 3. 如果邮箱也找不到，尝试用手机号登录
        if user is None:
            try:
                user = User.objects.get(phone=username)
            except User.DoesNotExist:
                pass

        # 4. 如果找到用户，验证密码和用户状态
        if user is not None and user.check_password(password) and self.user_can_authenticate(user):
            return user

        return None

    def get_user(self, user_id):
        """
        根据用户ID获取用户对象
        :param user_id: 用户ID
        :return: 用户对象或None
        """
        try:
            user = User.objects.get(pk=user_id)
            return user if self.user_can_authenticate(user) else None
        except User.DoesNotExist:
            return None
